package cn.edu.swust.adressbook.activity;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import cn.edu.swust.adressbook.R;
import cn.edu.swust.adressbook.adapter.ContactItemAdapter;
import cn.edu.swust.adressbook.bean.Contact;
import cn.edu.swust.adressbook.service.IBaseService;
import cn.edu.swust.adressbook.service.impl.ContactServiceImpl;
import cn.edu.swust.adressbook.utils.PinyinUtil;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String CANCEL = "取消";
    public static final String DELETE = "删除";
    public static final String EDIT = "编辑";
    public static final String ADD = "添加";
    public static final String NULL = "";
    public static final String PERSON = "person";
    private ListView mContactsList;     ///< 联系人列表
    private TextView mSearchEdit;         ///< 查询输入框
    private List<Contact> mBaseContacts;///< 所有联系人
    private List<Contact> mContacts;    ///< 查询结果
    private ContactItemAdapter mItemAdapter;///< 联系人适配器
    private TextView mAddButton;            ///< 添加联系人按钮
    private TextView mEditAllButton;        ///< 批量编辑联系人
    private TextView mHeadWord;             ///< 引导栏
    private boolean mIsEditAll = false;     ///< 是否全部编辑
    private IBaseService mContactService;   ///< 数据库接口
    private TextView mSelectText;           ///< 多选的数量提醒

    public MainActivity(){
        mContacts = new ArrayList<>();

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContactService = new ContactServiceImpl(MainActivity.this);
        initView();
        initData();

        setButtonListener();
        setSearchListener();
        setListScrollListener();
        setListItemOnclickListener();

    }


    //list item 监听
    private void setListItemOnclickListener() {
        mContactsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //跳转到详情
                if(mIsEditAll){
                    mSelectText.setText("已选择("+mContactsList.getCheckedItemIds().length + "/" + mContacts.size() +")");
                } else {
                    Contact contact = mContacts.get(i);
                    Intent intent = new Intent(MainActivity.this,DetailsActivity.class);
                    intent.putExtra(PERSON,contact);
                    startActivity(intent);
                }
            }
        });
    }

    //list滚动监听
    private void setListScrollListener() {
        mContactsList.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
                updateHeadWord();
            }
        });
    }

    //搜索栏监听器
    private void setSearchListener() {
        mSearchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                updateList();
            }
        });
    }

    //初始化数据
    private void initData() {
        mBaseContacts = mContactService.getAll();
        mItemAdapter = new ContactItemAdapter(MainActivity.this);
        updateList();
    }

    //更新联系人列表
    private void updateList() {
        String input = PinyinUtil.getPingYin(mSearchEdit.getText().toString());
        mContacts.clear();
        boolean isSearch = true;
        if("".equals(input)){
            isSearch = false;
        }
        for (int i = 0; i < mBaseContacts.size(); i++) {
            if(!isSearch || mBaseContacts.get(i).getPinyin().contains(input)) {
                mContacts.add(mBaseContacts.get(i));
            }
        }
        mItemAdapter.setContacts(mContacts);
        mContactsList.setAdapter(mItemAdapter);
        updateHeadWord();
    }

    //更新引导栏
    private void updateHeadWord() {
        if(mContacts.size() == 0){
            mHeadWord.setVisibility(View.GONE);
        } else {
            mHeadWord.setVisibility(View.VISIBLE);
            mHeadWord.setText(String.valueOf(mContacts.get(mContactsList.getFirstVisiblePosition()).getPinyin().charAt(0)));
        }
    }

    //得到view
    private void initView() {

        mSearchEdit = (TextView) findViewById(R.id.search_text);
        mContactsList = (ListView) findViewById(R.id.phone_lists);
        mEditAllButton = (TextView) findViewById(R.id.edit_all_button);
        mAddButton = (TextView) findViewById(R.id.add_btn);
        mHeadWord = (TextView) findViewById(R.id.first_word);
        mSelectText = (TextView) findViewById(R.id.select_count);
        findViewById(R.id.select_layout).setVisibility(View.GONE);
    }

    //建立监听事件
    private void setButtonListener() {
        mEditAllButton.setOnClickListener(this);
        mAddButton.setOnClickListener(this);
        findViewById(R.id.group_button).setOnClickListener(this);
        findViewById(R.id.all_button).setOnClickListener(this);
        findViewById(R.id.edit_button).setOnClickListener(this);
    }



    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.edit_button:
            case R.id.edit_all_button:
                //TODO: to edit many list item
                editAllOrCancel();
                break;
            case R.id.group_button:
                //TODO: intent group activity
                startActivity(new Intent(MainActivity.this, GroupActivity.class));
                break;
            case R.id.add_btn:
                //TODO: intent add activity or delete
                startActivity(new Intent(MainActivity.this,EditActivity.class));
                addOrDelete();
                break;
            case R.id.all_button:
                break;
            default:
                break;

        }
    }


    private void addOrDelete() {
        if (mIsEditAll){ // 删除完毕后更新显示
            long[] contactItemIds = mContactsList.getCheckedItemIds();
            for (int i = 0; i < contactItemIds.length; i++) {
                mContactService.delete(mContacts.get((int) contactItemIds[i]));
            }
            initData();
            editAllOrCancel();
        } else {
            //TODO: intent add activity
            startActivity(new Intent(MainActivity.this, AddActivity.class));
        }
    }

    private void editAllOrCancel() {
        mIsEditAll = !mIsEditAll;
        if (mIsEditAll){
            mSelectText.setText("已选择("+mContactsList.getCheckedItemIds().length + "/" + mContacts.size() +")");
            findViewById(R.id.search_layout).setVisibility(View.GONE);
            findViewById(R.id.select_layout).setVisibility(View.VISIBLE);
            mEditAllButton.setText(CANCEL);
            mAddButton.setText(DELETE);
        } else {
            findViewById(R.id.search_layout).setVisibility(View.VISIBLE);
            findViewById(R.id.select_layout).setVisibility(View.GONE);
            mEditAllButton.setText(EDIT);
            mAddButton.setText(ADD);
        }
        mItemAdapter.setNeedCheck(mIsEditAll);
        mSearchEdit.setText(NULL);
        updateList();
    }

    @Override
    protected void onResume() {
        super.onResume();

        mSearchEdit.setText("");
        mContactService = new ContactServiceImpl(this);
        mBaseContacts = mContactService.getAll();
        updateList();
    }
}